<template>
  <PublicPage :borderType="true" :showNav="true" :custoNav="true">
    <!-- 自定义头部 -->
    <template v-slot:headNav>
      <view class="tc u-flex" style="height:100%;">
        <view class="u-p-l-20" @click="navigateBack({delta: 1})" style="flex-shrink: 0;width:60rpx;">
          <image style="width:40rpx;height:40rpx;" src="@/static/image/navBack_icon.png" />
        </view>
        <view class="tc fw5" style="flex:1;" :style="'padding-left:'+globalData.menuButtonObject.width+'rpx;'">
          <view class="fz-14">{{receiverUser.userName}}</view>
          <view class="fz-12 viceColor">{{receiverUser.communityName || ''}}</view>
        </view>
      </view>
    </template>
    <view class="messageDetails" :style="{paddingBottom: inputBottom + 'px'}">
      <!-- 聊天窗口 -->
      <scroll-view scroll-y :scroll-into-view="toView" class="scrollHeight" :scroll-top="scrollTop" @scrolltoupper="loadMove">
        <view v-for="(msg,msgIdx) in msgList" :key="msgIdx" :id="'item'+msgIdx">
          <view class="u-p-b-20" v-if="!msg.disableNotification">
            <view class="tc fz-12 viceColor u-p-b-20 u-p-t-10" v-if="showTime(msg,msgIdx)">{{msgToggleTime(msg.sentTime)}}</view>
            <!-- msg.messageDirection === 2 ? 他人 : 自己 -->
            <view class="msgBody" :class="msg.messageDirection === 2 ? 'leftBox' : 'rightBox'">
              <view class="userImgBox" :class="msg.messageDirection === 2 ? 'u-m-l-16' : 'u-m-r-16'">
                  <image class="imgs" :src="msg.messageDirection === 2 ? receiverUser.userPortrait : imUserInfo.userPortrait" />
              </view>
              <view class="contentBox">
                {{msg.content.content}}
                <u-icon name="play-left-fill" class="jiantou2" color="#FFFFFF" size="24" v-if="msg.messageDirection === 2" />
                <u-icon name="play-right-fill" class="jiantou1" color="#FFFFFF" size="24" v-else />
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
      <view class="sengBtnBox" :class="{sendBottom: !inputBottom}" :style="{ bottom: inputBottom + 'px' }">
        <view style="flex:1;">
        <!-- <u-input v-model="textContent" type="text" :clearable="false" placeholder="请输入消息" :custom-style="{'marginBottom': '25rpx;','borderRadius': '8rpx','padding': '0 20rpx;','background': '#F2F3F5','height': '80rpx'}" />-->
          <input
              v-model="textContent"
              type="text" placeholder="请输入消息"
              confirm-type="send"
              :adjust-position="false"
              class="inputContent"
              @focus="_inputFocus"
              @blur="_inputBlur"
              @confirm="sendMessage"
          />
        </view>
        <view class="sengBtn" @click="sendMessage">
          <image src="https://qqposs.oss-cn-shenzhen.aliyuncs.com/mpAppImg/icon/zhiding5_icon.png" style="width:48rpx;height:auto;" mode="widthFix" />
        </view>
      </view>
    </view>
  </PublicPage>
</template>
<script>
import PublicPage from "@/components/publicPage/index.vue";
import { getImUserInfo } from "@/utils/rongIMLib/user.js";
import { msgToggleTime } from "@/utils/formTime.js"

export default {
  components: {
    PublicPage
  },
  computed: {
    globalData () {
      return this.$store.state.globalData
    },
    // 自己IM信息
    imUserInfo() {
      return this.$store.state.imUserInfo
    },
    // 当前会话用户
    receiverUser(){
      return this.$store.state.receiverUser
    },
    // 当前会话的历史消息
    msgList(){
      return this.$store.state.msgList
    }
  },
  onLoad(options){
    this.routeData = options
    this.getUserInfo()
    this.getMessageList()
  },
  // 离开页面，用户信息和会话列表不一致，且没有发消息更新，手动发送一条跟最后一条消息一样的消息
  onUnload(){
    const that = this
    const oldUser = that.$store.state.clickImUser
    const newNuser = that.receiverUser
    if(oldUser.userPortrait !== newNuser.userPortrait || oldUser.userName !== newNuser.userName || oldUser.communityName !== newNuser.communityName){
      console.log('用户信息有更新');
      if(!this.isSendMsg){
        console.log('并且未发送新消息');
        const currenItem = that.msgList[that.msgList.length -1]
        // 发送更新用户消息,不展示
        const conversation = that.$im.Conversation.get({
          targetId: that.routeData.id, // 接受者用户ID
          type: 1 // 聊天类型 1单聊 3群聊 4聊天室 6系统
        });

        // 删除静默消息
        that.disableList.length && conversation.deleteMessages(that.disableList).then(res=>{console.log('删除静默消息成功');})
        conversation.send({
          messageType: 'RC:TxtMsg', // RC:TxtMsg RC:ImgMsg RC:ImgTextMsg  
          content: { // 填写开发者定义的消息内容
            content: currenItem?.content?.content ?? '', // 内容
            sendUserName: that.imUserInfo.userName, // 发送人用户名
            sendCommunityName: that.imUserInfo.communityName, // 发送人社群名称
            sendUserImg: that.imUserInfo.userPortrait, // 发送人用户头像
            receiverUserName: that.receiverUser.userName,  // 接收人用户名
            receiverCommunityName: that.receiverUser.communityName, // 接收人社群名称
            receiverUserImg: that.receiverUser.userPortrait, // 接收人用户头像
          },
          isPersited: false, // 是否存储再服务端
          isCounted: false,  // 是否计数. 计数消息接收端接收后未读数加 1，默认为 true
          disableNotification: true // 是否为静默消息
        }).then(res=>{console.log('发送静默消息成功');})
      }
    }
  },
  data(){
    return {
      routeData: {},
      currentPage: 1,
      hasMore: true, // 是否还有历史消息可以获取，
      textContent: "", // 输入内容
      toView: '',
      inputBottom: 0, // 弹起键盘高度
      scrollTop: 1000, // 弹起键盘时消息滚动到最下一条
      isSendMsg: false, // 是否有发送消息
      disableList: [], // 静默消息数组，只会存在一条
    }
  },
  methods:{
    msgToggleTime,
    // 查询用户信息
    getUserInfo(){
      getImUserInfo(this.routeData.id).then(userInfo=>{
        this.$store.commit('SET_RECEIVERUSER',userInfo)
      })
    },
    // 获取当前用户的历史消息
    getMessageList(){
      const that = this
      let conversation = this.$im.Conversation.get({
        targetId:  that.routeData.id,
        type: that.$RongIMLib.CONVERSATION_TYPE.PRIVATE
      });
      let option = {
        timestamp: +(that.currentPage === 1 ? new Date() : that.msgList[0].sentTime),
        count: 15
      };
      conversation.getMessages(option).then(function(result){
        console.log(result.list,'历史消息');
        if(that.currentPage === 1){ // 首次获取
          that.$store.commit('SET_MESSAGE_LIST',result.list)
          conversation.read().then(function(){
            console.log('清除未读数成功'); // im.watch conversation 将被触发
          });
          that.goBottom()

          if(result.list.length && result.list[result.list.length-1].disableNotification){
            that.disableList.push(result.list[result.list.length-1])
          }
        }else{ // 加载更多
          that.$store.commit('SET_MESSAGE_LIST',[...result.list,...that.msgList])
        }
        that.hasMore = result.hasMore; // 是否还有历史消息可以获取
      });
      
    },
    // 获取更多历史消息
    loadMove(){
      if(this.hasMore){ // 还有更多
        this.currentPage++
        this.getMessageList()
      }
    },
    // 发送消息
    sendMessage() {
      const that = this
      if(!that.textContent) return
      const conversation = that.$im.Conversation.get({
        targetId: that.routeData.id, // 接受者用户ID
        type: 1 // 聊天类型 1单聊 3群聊 4聊天室 6系统
      });
      conversation.send({
        messageType: 'RC:TxtMsg', // RC:TxtMsg RC:ImgMsg RC:ImgTextMsg  
        content: { // 填写开发者定义的消息内容
          content: that.textContent, // 内容
          sendUserName: that.imUserInfo.userName, // 发送人用户名
          sendCommunityName: that.imUserInfo.communityName, // 发送人社群名称
          sendUserImg: that.imUserInfo.userPortrait, // 发送人用户头像
          receiverUserName: that.receiverUser.userName,  // 接收人用户名
          receiverCommunityName: that.receiverUser.communityName, // 接收人社群名称
          receiverUserImg: that.receiverUser.userPortrait, // 接收人用户头像
        },
        isCounted: true  // 是否计数. 计数消息接收端接收后未读数加 1，默认为 true
      }).then(function(message){
        const newMsgList = [...that.msgList,message]
        that.$store.commit('SET_MESSAGE_LIST',newMsgList) // 添加进当前页面的历史消息
        that.goBottom()
        that.textContent = ''
        that.isSendMsg = true
        console.log('发送IM消息成功', message);
      });
    },
    // 回到最底部
    goBottom(){
      this.$nextTick(()=>{
        this.toView = `item${this.msgList.length-1}`
      })
    },
    // 是否显示时间
    showTime(msg,msgIdx){
      if(msgIdx === 0){
        return true
      }else{
        if((msg.sentTime - this.msgList[msgIdx-1].sentTime) > 180000){ // 距离上一条三分钟内不显示，直到出现断层
          return true
        }else{
          return false
        }
      }
    },
    // input获取焦点时--获取弹出键盘的高度
    _inputFocus(e) {
      console.log(e.detail)
      this.inputBottom = e.detail.height
      this.scrollTop += 1
      console.log(e.detail)
    },
    _inputBlur() {
      this.inputBottom = 0
    }
  }
}
</script>
<style lang="scss" scoped>
.messageDetails{
  height: 100%;
  .scrollHeight{
    height: calc(100% - 140rpx);
  }
  .msgBody{
    display: flex;
    .userImgBox{
      width: 80rpx;
      height: 80rpx;
      border-radius: 8rpx;
      background-color: #C4C4C4;
      overflow: hidden;
      flex-shrink: 0;
      .imgs{
        width: 80rpx;
        height: 80rpx;
      }
    }
    .contentBox{
      max-width: 50%;
      background-color: #FFF;
      border-radius: 8rpx;
      line-height: 40rpx;
      color: #000;
      padding: 20rpx 16rpx;
      word-break:break-all;
      position: relative;
      .jiantou1{
        display: block;
        position: absolute;
        right: -15rpx;
        top: 50%;
        transform: translateY(-50%);
      }
      .jiantou2{
        display: block;
        position: absolute;
        left: -15rpx;
        top: 50%;
        transform: translateY(-50%);
      }
    }
  }
  .msgBody.leftBox{
    flex-direction: row;
    .contentBox{
      margin-left: 20rpx;
    }
  }
  .msgBody.rightBox{
    flex-direction: row-reverse;
    .contentBox{
      margin-right: 20rpx;
    }
  }

  .sengBtnBox{
    display: flex;
    position: fixed;
    width: 100%;
    bottom: 0;
    left: 0;
    padding: 25rpx 30rpx;
    padding-right: 0;
    background: #FFF;
    box-shadow: inset 0px 1px 0px #EEEEEE;
    .inputContent {
      height: 80rpx;
      padding: 0 20rpx;
      margin-bottom: 25rpx;
      border-radius: 8rpx;
      background-color: #F2F3F5;
    }
    .sengBtn{
      padding-top: 18rpx;
      padding-left: 32rpx;
      padding-right: 32rpx;
    }
    &.sendBottom {
      padding-bottom: 0;
      padding-bottom: constant(safe-area-inset-bottom);
      padding-bottom: env(safe-area-inset-bottom);
    }
  }
}

</style>
<style scoped>
.messageDetails >>> .u-input{
  padding: 0 !important;
}
</style>